package com.wcs.spring.util;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang.StringUtils;

public class WeekDateUtil {

	private static final int FIRST_DAY = Calendar.MONDAY;

	public static List<String> getWeekdays2(String dateString) {
		List<String> list = new ArrayList<String>();
		Calendar calendar = Calendar.getInstance();
		if (StringUtils.isNotBlank(dateString)) {
			Date date = null;
			try {
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
				date = sdf.parse(dateString);
				calendar.setTime(date);
			}
			catch (ParseException e) {
				System.out.println(e.getMessage());
			}
		}

		setToFirstDay(calendar);
		for (int i = 0; i < 7; i++) {
			list.add(printDay(calendar));
			calendar.add(Calendar.DATE, 1);
		}

		return list;
	}

	public static List<String> getWeekdays(Date date) {
		List<String> list = new ArrayList<String>();
		Calendar calendar = Calendar.getInstance();
		if (null != date) {
			calendar.setTime(date);
		}

		setToFirstDay(calendar);
		for (int i = 0; i < 7; i++) {
			list.add(printDay(calendar));
			calendar.add(Calendar.DATE, 1);
		}

		return list;
	}

	private static void setToFirstDay(Calendar calendar) {
		while (calendar.get(Calendar.DAY_OF_WEEK) != FIRST_DAY) {
			calendar.add(Calendar.DATE, -1);
		}
	}

	private static String printDay(Calendar calendar) {
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
		return dateFormat.format(calendar.getTime());
	}

	public static String dateToString(Date date, String format) {
		SimpleDateFormat dateFormat = new SimpleDateFormat(format);
		return dateFormat.format(date);
	}

}
